package cn.com.dhcc.app.pub.core.util;

import java.io.StringReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;

/**
 * 生成节点列表xml
 * 
 * @日期：2014-8-5 上午10:59:25
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
public class NodeXmlUtil{
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getDetachLogger(LOGTYPE.TURBO);
	/**
	 * 节点关系图xml 根据节点id在节点关系图xml中筛选关系节点，重新生成关系图
	 * @param nodeId 节点id
	 * @param xmlDoc 节点关系图xml
	 * @return
	 */
	@SuppressWarnings({ "rawtypes"})
	public static String forExchRelXML(String nodeId,String xmlDoc) {
		StringBuilder exchRelXML = new StringBuilder();
		  // 创建一个新的字符串
		  StringReader read = new StringReader(xmlDoc);
		  // 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
		  InputSource source = new InputSource(read);
		  // 创建一个新的SAXBuilder
		  SAXBuilder sb = new SAXBuilder();
		  try {
		   // 通过输入源构造一个Document
		   Document doc = sb.build(source);
		   // 取的根元素
		   Element root = doc.getRootElement();
		   // 得到根元素所有子元素的集合
		   List jiedian = root.getChildren();
		   if(jiedian.size() > 0){
			   // 获得XML中的命名空间（XML中未定义可不写）
//			   Namespace ns = root.getNamespace();
//			   Element et = null;
			   /**
			     * 如要取<rel>下的子元素的名称
			     */
//			   et = (Element) jiedian.get(0);
			   StringBuilder lines = new StringBuilder();
			   Set<String> set = new HashSet<String>();
			   List line = root.getChildren("line");
			   for (int i = 0; i < line.size(); i++) {
				    Element lineEt = (Element) line.get(i);
				    if(nodeId.equals(lineEt.getAttributeValue("fromNode")) || nodeId.equals(lineEt.getAttributeValue("toNode"))){
				    	lines.append("<line");
				    	lines.append(" name='").append(lineEt.getName()).append("'");
				    	lines.append(" startX='").append(lineEt.getAttributeValue("startX")).append("'");
				    	lines.append(" startY='").append(lineEt.getAttributeValue("startY")).append("'");
				    	lines.append(" endX='").append(lineEt.getAttributeValue("endX")).append("'");
				    	lines.append(" endY='").append(lineEt.getAttributeValue("endY")).append("'");
				    	lines.append(" fromNode='").append(lineEt.getAttributeValue("fromNode")).append("'");
				    	lines.append(" toNode='").append(lineEt.getAttributeValue("toNode")).append("'");
				    	lines.append(" fromIcon='").append(lineEt.getAttributeValue("fromIcon")).append("'");
				    	lines.append(" toIcon='").append(lineEt.getAttributeValue("toIcon")).append("'");
				    	lines.append(" isEdit='").append(lineEt.getAttributeValue("isEdit")).append("' />");
				    	set.add(lineEt.getAttributeValue("fromNode"));
				    	set.add(lineEt.getAttributeValue("toNode"));
				    }
			   }
			   StringBuilder nodes = new StringBuilder();   
			   List node = root.getChildren("node");
			   for (int i = 0; i < node.size(); i++) {
				    Element nodeEt = (Element) node.get(i);
				    if(set.contains(nodeEt.getAttributeValue("nodeId"))){
				    	nodes.append("<node");
					    nodes.append(" nodeId='").append(nodeEt.getAttributeValue("nodeId")).append("'");
					    nodes.append(" name='").append(nodeEt.getAttributeValue("name")).append("'");
					    nodes.append(" label='").append(nodeEt.getAttributeValue("label")).append("'");
					    nodes.append(" type='").append(nodeEt.getAttributeValue("type")).append("'");
					    nodes.append(" selected='").append(nodeEt.getAttributeValue("selected")).append("'");
					    nodes.append(" x='").append(nodeEt.getAttributeValue("x")).append("'");
					    nodes.append(" y='").append(nodeEt.getAttributeValue("y")).append("'");
					    nodes.append(" isCurrent='").append(nodeEt.getAttributeValue("isCurrent")).append("'");
					    nodes.append(" isEdit='").append(nodeEt.getAttributeValue("isEdit")).append("' />");
				    }
			   }
			   exchRelXML.append("<rel>").append(nodes.toString()).append(lines.toString()).append("</rel>");
		   	}
		  } catch (Exception e) {
			  logger.error(e);
		  }
		  return exchRelXML.toString();
	}
	
//	@SuppressWarnings("null")
//	public static void main(String[] args) {
//		String xml = "<rel>"
//							+"		<node nodeId='ebf21e13760f44bb804ad1ee9a735b56' label='开始' type='8' selected='false' memo='' x='371' y='162' iscurrent='ture'/>"
//							+"		<node nodeId='ebf21e13760dd4bb804ad1ee9a735b56' label='分支1' type='6' selected='false' memo='' x='135' y='332' iscurrent='false'/>"
//							+"		<node nodeId='f47456f589c14868b8b64bc30c01f1b1' label='分支2' type='6' selected='true' memo='' x='580' y='352' iscurrent='false'/>"
//							+"		<node nodeId='f47456f589a14868b8b64bc30c01f1ba' label='分支3' type='6' selected='true' memo='' x='580' y='352' iscurrent='false'/>"
//							+"		<line name='Line7226576258' startX='387' startY='178' endX='168' endY='332' fromNode='ebf21e13760f44bb804ad1ee9a735b56' toNode='ebf21e13760dd4bb804ad1ee9a735b56' fromIcon='START' toIcon='Node8743492147'/>"
//							+"		<line name='Line5287972926' startX='387' startY='178' endX='580' endY='352' fromNode='ebf21e13760f44bb804ad1ee9a735b56' toNode='f47456f589c14868b8b64bc30c01f1b1' fromIcon='START' toIcon='Node7751661751'/>"
//							+"		<line name='Line5287972925' startX='387' startY='170' endX='581' endY='351' fromNode='ebf21e13760f44bb804ad1ee9a735b56' toNode='f47456f589a14868b8b64bc30c01f1ba' fromIcon='START' toIcon='Node7751661752'/>"
//							+"	</rel>";
//		String nodeId = "ebf21e13760f44bb804ad1ee9a735b56";
//		System.out.println(forExchRelXML(nodeId,xml));
//		HttpServletResponse response = null;
//		String id = "ebf21e13760f44bb804ad1ee9a735b56";
//		try {
//			NodeInfo vo = new NodeInfo();
//			vo.setId(id);
//			vo.setNodeCode("120000000");
//			vo.setNodeName("天津");
//			vo.setPid("f47456f589c14868b8b64bc30c01f1b1");
//			//封装xml格式数据
//			XStream xstream = new XStream();
//			xstream.alias("node", NodeInfo.class);
//			String  rstVal = xstream.toXML(vo);
//			//结果数据输出
//			OutputStream outputStream = response.getOutputStream();
//			response.setContentType("text/xml;charset=UTF-8");
//			FileCopyUtils.copy(rstVal, new OutputStreamWriter(outputStream, "UTF-8"));
//			outputStream.flush();
//			response.flushBuffer();
//			if (outputStream != null)
//				outputStream.close();
//		} catch (Exception e) {
//			logger.error(e);
//		}
//	}
}
